<template>
  <div class="app-container">

    <!--<el-button type="cyan" icon="el-icon-search" size="mini" @click="getList">查询</el-button>
    <el-button
      type="primary" plain
      icon="el-icon-upload2"
      size="mini"
      @click="uploadTool"
    >导入</el-button>-->

  <el-calendar v-model="value">
    <template @click.native="uploadTool"
      slot="dateCell"
      slot-scope="{date, data}">
      <div :class="data.isSelected ? 'is-selected' : ''">
        <!--{{ data.day }} {{ data.isSelected ? '✔️' : ''}}-->
        {{ data.day.split('-').slice(2).join('-') }}
        <div style="padding-top: 0px; text-align: left;">
          <!--<p v-for="(scale, supplier) in diskScales[data.day]">
            <span style="color: #909399; font-size: 8px;">{{ supplierDict[supplier] + " " }}</span><span style="font-size: 14px; font-weight: bold;">{{ scale + " " }}</span>
          </p>-->
          <el-link v-if="diskScales[data.day]" type="primary" icon="el-icon-view" :underline="false" @click="handleEdit(data.day)">查看</el-link>
          <el-link v-else type="info" icon="el-icon-edit" :underline="false" @click="handleEdit(data.day)" style="margin-left: 5px;">修改</el-link>
        </div>
      </div>
    </template>
  </el-calendar>

  <!-- 用户导入对话框 -->
  <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
    <el-upload
      ref="upload"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">
        <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
      </div>
      <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="upload.open = false">取 消</el-button>
    </div>
  </el-dialog>

  <!-- 添加或修改参数配置对话框 -->
  <el-dialog :title="edit.title" :visible.sync="edit.open" width="800px" append-to-body>
    <el-form ref="form" :model="edit.formData" :rules="rules" label-width="220px">
      <el-row>
        <el-col :span="12" v-for="(scaleDomain, index) in edit.formData.datas">
          <el-form-item :label="supplierMap[scaleDomain.supplier] + ' ' + diskMap[scaleDomain.serverCode]" prop="_scale">
            <el-input type="number" v-model="scaleDomain.diskScale" placeholder="请输入存储系数"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>
  </el-dialog>

  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { importTemplate, listDiskScales, saveBatch } from '@/api/basic/diskScale'
  import { supplierList, chargedMonths } from '@/api/basic/services'
  import { parseTime } from '@/utils/ruoyi'
  import {
    CatalogList
  } from "@/api/basic/services";

  export default {
    data() {
      let supplierMap = {}, diskMap = {}, defaultOption = [];
      supplierList({
        pageNum: 1, pageSize: 100
      }).then(response => {
        if(response.rows){
          for(let i in response.rows){
            supplierMap[response.rows[i].cloudSupplier] = response.rows[i].cloudSupplierName;
          }
        }
      }).then(() => {
        //盘类型
        CatalogList({ serviceNumber: "cc" }).then((response) => {
          if(response.rows){
            for(let i in response.rows){
              diskMap[response.rows[i].code] = response.rows[i].serviceName;
            }
            for(let supplier in supplierMap){
              for(let serverCode in diskMap){
                defaultOption.push({
                  supplier: supplier,
                  serverCode: serverCode,
                  diskScale: 1.0000
                });
              }
            }
          }
        });
      });

      return {
        value: new Date(),
        loading: false,
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: '',
        },
        edit: {
          open: false,
          title: "",
          formData: {
            effectDate: '',
            datas: {}
          }
        },
        diskScales: {},
        supplierMap: supplierMap,
        diskMap: diskMap,
        defaultOption: defaultOption,
        rules: {
        },
        dateRange: [],
      }
    },
    watch:{
      value(val, oldVal){//监听月份变化，重新加载数据
        if(val.getMonth()!=oldVal.getMonth() || val.getFullYear()!=oldVal.getFullYear()){
          this.buildDateRange();
          this.getList();
        }
      },
    },
    mounted() {
      this.drawLine();
    },
    created() {
      this.buildDateRange();
      this.getList();
    },
    methods: {
      drawLine(){
      },
      buildDateRange(now){
        now = now || this.value;
        let nowMonth = now.getMonth(); //当前月
        let nowYear = now.getFullYear(); //当前年
        let monthStartDate = new Date(nowYear, nowMonth, 1-7);
        let monthEndDate = new Date(nowYear, nowMonth+1, 0+7);
        this.dateRange = [parseTime(monthStartDate, "{y}-{m}-{d}"), parseTime(monthEndDate, "{y}-{m}-{d}")];
        return this.dateRange;
      },
      /** 导入按钮操作 */
      uploadTool() {
        this.upload.url = process.env.VUE_APP_BASE_API + "/import/diskScale",
        this.upload.title = "导入计费系数";
        this.upload.open = true;
        this.upload.remarks = "";
      },
      getList(){//查询一段时间的数据
        this.loading = true;
        listDiskScales({
          pageNum: 1,
          pageSize: 50,
          dateStart: this.dateRange[0],
          dateEnd: this.dateRange[1]
        }).then(response => {
          this.diskScales = response.data;
          this.loading = false;
        });
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();

        if(!response.success){
          this.$message.error(response.msg);
        }else{
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        }
        this.getList();
      },
      handleEdit(date){
        this.edit.title = "请输入 "+date+" 计费系数";
        this.edit.open = true;
        this.edit.formData.effectDate = date;
        this.edit.formData.datas = JSON.parse(JSON.stringify(this.diskScales[date] || this.defaultOption));
        for(let i in this.edit.formData.datas){
          this.edit.formData.datas[i].effectDate = date;
        }
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (!this.edit.formData.datas || !valid) {
            return;
          }
          saveBatch(this.edit.formData.datas).then(res => {
            if(res.success){
              this.msgSuccess(res.msg);
            }else{
              this.$message.error(res.msg);
            }
            this.edit.open = false;
            this.getList();
          });
        });
      },
      // 取消按钮
      cancel() {
        this.edit.open = false;
      },
    }
  }
</script>
<style>
  .is-selected {
    color: #1989FA;
    height: 100%;
  }
</style>
